package com.huawei.petapp2.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatButton;
import androidx.appcompat.widget.AppCompatEditText;
import androidx.appcompat.widget.AppCompatTextView;

import com.huawei.hmf.tasks.OnFailureListener;
import com.huawei.hmf.tasks.OnSuccessListener;
import com.huawei.hmf.tasks.Task;
import com.huawei.hms.common.ApiException;
import com.huawei.hms.support.hwid.HuaweiIdAuthManager;
import com.huawei.hms.support.hwid.request.HuaweiIdAuthParams;
import com.huawei.hms.support.hwid.request.HuaweiIdAuthParamsHelper;
import com.huawei.hms.support.hwid.result.AuthHuaweiId;
import com.huawei.hms.support.hwid.service.HuaweiIdAuthService;
import com.huawei.hms.support.hwid.ui.HuaweiIdAuthButton;
import com.huawei.petapp2.R;
import com.huawei.petapp2.constant.HttpAddress;
import com.huawei.petapp2.constant.SPConstants;
import com.huawei.petapp2.entity.Result;
import com.huawei.petapp2.entity.User;
import com.huawei.petapp2.utils.DateUtil;
import com.huawei.petapp2.utils.PreferenceHelper;
import com.huawei.petapp2.utils.SPUtil;

import org.json.JSONException;
import org.json.JSONObject;

public class LoginActivity extends AppCompatActivity implements View.OnClickListener {

    public static final int REQUEST_SIGN_IN_LOGIN = 1002;
    private static final String TAG = "LoginActivity";
    private ImageView login_logo_image;
    private ImageView title_back;
    private AppCompatTextView title_name;
    private AppCompatEditText login_username;
    private ImageView login_username_del;
    private AppCompatEditText login_password;
    private ImageView login_password_del;
    private TextView login_register;
    private AppCompatButton login_login;
    private TextView login_agreement;
    private TextView login_otherLogin;
    private HuaweiIdAuthButton hwid_signin;
    // 华为账号登录客户端
    private HuaweiIdAuthService mAuthService;

    private PreferenceHelper preferenceHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        initView();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_back:
                // 返回
                finish();
                break;
            case R.id.login_login:
                // 登录
                onLogin();
                break;
            case R.id.login_forget:
                // 忘记密码
                forgetPassword();
              //  Toast.makeText(this, "请使用快速登录方式，无需注册", Toast.LENGTH_SHORT).show();
                break;
            case R.id.hwid_signin:
                // 华为账号登录
                silentSignIn();
                break;
            case R.id.login_username_del:
                // 输入账号信息-删除
                login_username.setText("");
                break;
            case R.id.login_password_del:
                // 输入密码信息-删除
                login_password.setText("");
                break;
            default:
                break;
        }
    }

    private void forgetPassword() {
        Intent intent=new Intent(LoginActivity.this,RegisterActivity.class);
        startActivity(intent);
      //  finish();
    }

    private void initView() {
        login_logo_image = (ImageView) findViewById(R.id.login_logo_image);
        title_back = (ImageView) findViewById(R.id.title_back);
        title_name = (AppCompatTextView) findViewById(R.id.title_name);
        login_username = (AppCompatEditText) findViewById(R.id.login_username);
        login_username_del = (ImageView) findViewById(R.id.login_username_del);
        login_password = (AppCompatEditText) findViewById(R.id.login_password);
        login_password_del = (ImageView) findViewById(R.id.login_password_del);
        login_register = (TextView) findViewById(R.id.login_forget);
        login_login = (AppCompatButton) findViewById(R.id.login_login);
        login_agreement = (TextView) findViewById(R.id.login_agreement);
        login_otherLogin = (TextView) findViewById(R.id.login_otherLogin);
        hwid_signin = (HuaweiIdAuthButton) findViewById(R.id.hwid_signin);

        title_back.setOnClickListener(this);
        login_register.setOnClickListener(this);
        login_login.setOnClickListener(this);
        hwid_signin.setOnClickListener(this);

        onTextChangedListener();
    }

    private void onLogin() {
        String username = login_username.getText().toString().trim();
        if (TextUtils.isEmpty(username)) {
            Toast.makeText(this, "请输入账号", Toast.LENGTH_SHORT).show();
            return;
        }

        String password = login_password.getText().toString().trim();
        if (TextUtils.isEmpty(password)) {
            Toast.makeText(this, "请输入密码", Toast.LENGTH_SHORT).show();
            return;
        }
        else{

            Result result =DateUtil.selectList(
                    HttpAddress.get(HttpAddress.user(),"login",password,username));
           // System.out.println(result.getResult());

            User users=DateUtil.getEntity(result,User.class);
            System.out.println("dayingduixiang"+users);
            if(result.getResult()!=null)
            {
                preferenceHelper.saveLoginInfo(this,users,result.getMsg());
                Toast.makeText(this, "欢迎登录", Toast.LENGTH_SHORT).show();
                Intent intent=new Intent(LoginActivity.this,HomeActivity.class);
                startActivity(intent);
            }
            else{
                Toast.makeText(this, "账号或密码错误", Toast.LENGTH_SHORT).show();
            }
            /*if(users==null)
            {
                Toast.makeText(this, "账号或密码错误", Toast.LENGTH_SHORT).show();
            }

             else if(users..equals(password))
            {
                preferenceHelper.saveLoginInfo(this,username,password);
                Toast.makeText(this, "欢迎登录", Toast.LENGTH_SHORT).show();
                Intent intent=new Intent(LoginActivity.this,HomeActivity.class);
                startActivity(intent);
               // finish();
            }
            else{
                Toast.makeText(this, "账号或密码错误", Toast.LENGTH_SHORT).show();
            }*/
           /*
            测试登录：Result result =DateUtil.selectList(
                    HttpAddress.get(HttpAddress.user(),"list"));
            List<User> users=DateUtil.getList(result);*/

           /*测试pet图片： Result results =DateUtil.selectList(
                    HttpAddress.get(HttpAddress.petshow(),"show"));
            List<Petshow> petshow=DateUtil.getList(results);
            //System.out.println(users.toString());
            System.out.println(petshow.get(0));*/
           /* Result result =DateUtil.selectList(
                    HttpAddress.get(HttpAddress.user(),"list"));
            List<User> users=DateUtil.getList(result);
*/
        }

    }

    /**
     * 静默登录
     */
    private void silentSignIn() {
        // 配置授权参数
        HuaweiIdAuthParams authParams = new HuaweiIdAuthParamsHelper(HuaweiIdAuthParams.DEFAULT_AUTH_REQUEST_PARAM)
                .createParams();
        // 初始化HuaweiIdAuthService对象
        mAuthService = HuaweiIdAuthManager.getService(LoginActivity.this, authParams);
        // 发起静默登录请求
        Task<AuthHuaweiId> task = mAuthService.silentSignIn();
        // 处理授权成功的登录结果
        task.addOnSuccessListener(new OnSuccessListener<AuthHuaweiId>() {
            @Override
            public void onSuccess(AuthHuaweiId authHuaweiId) {
                // 已经授权
                onHuaweiIdLoginSuccess(authHuaweiId);
                Log.d(TAG, authHuaweiId.getDisplayName() + "静默登录成功");
            }
        });
        // 处理授权失败的登录结果
        task.addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(Exception e) {
                if (e instanceof ApiException) {
                    ApiException apiException = (ApiException) e;
                    if (apiException.getStatusCode() == 2002) {
                        // 未授权，调用onHuaweiIdLogin方法拉起授权界面，让用户授权
                        onHuaweiIdLogin();
                    }
                }
            }
        });
    }

    /**
     * 保存用户信息到SharedPreferences
     */
    private void onHuaweiIdLoginSuccess(AuthHuaweiId huaweiAccount) {
        // 保存华为账号 openId
        String openId = huaweiAccount.getOpenId();
        System.out.println("my open id:------------  "+openId+"------------my open id ");
        SPUtil.put(this, SPConstants.KEY_HW_OEPNID, openId);
        try {
            JSONObject jsonObject = new JSONObject();
            // 保存华为帐号头像
            jsonObject.put(SPConstants.KEY_HEAD_PHOTO, huaweiAccount.getAvatarUriString());
            SPUtil.put(this, openId, jsonObject.toString());
        } catch (JSONException ignored) {
            Log.e(TAG, "onHuaweiIdLoginSuccess json format error");
        }
        // 是否登录
        SPUtil.put(this, SPConstants.KEY_LOGIN, true);
        // 华为登录
        SPUtil.put(this, SPConstants.KEY_HW_LOGIN, true);
        // 保存华为帐号昵称
        SPUtil.put(this, SPConstants.KEY_NICK_NAME, huaweiAccount.getDisplayName());
        Intent intent=new Intent(LoginActivity.this,HomeActivity.class);
        startActivity(intent);
        //finish();
    }

    /**
     * 华为账号登录
     */
    private void onHuaweiIdLogin() {
        // 构造华为账号登录选项
        HuaweiIdAuthParams authParam = new HuaweiIdAuthParamsHelper(HuaweiIdAuthParams.DEFAULT_AUTH_REQUEST_PARAM)
                .createParams();

        mAuthService = HuaweiIdAuthManager.getService(LoginActivity.this, authParam);

        // 获取登录授权页面的Intent，并通过startActivityForResult拉起授权页面
        startActivityForResult(mAuthService.getSignInIntent(), REQUEST_SIGN_IN_LOGIN);
    }

    private void onTextChangedListener() {
        login_username.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                String text = s.toString().trim();
                if (TextUtils.isEmpty(text)) {
                    login_username_del.setVisibility(View.INVISIBLE);
                } else {
                    login_username_del.setVisibility(View.VISIBLE);
                }
            }
        });

        login_password.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                String text = s.toString().trim();
                if (TextUtils.isEmpty(text)) {
                    login_password_del.setVisibility(View.INVISIBLE);
                } else {
                    login_password_del.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != Activity.RESULT_OK) {
            Log.d(TAG, "onActivityResult: not OK!");
            return;
        }

        if (requestCode == REQUEST_SIGN_IN_LOGIN) {
            Task<AuthHuaweiId> authHuaweiIdTask = HuaweiIdAuthManager.parseAuthResultFromIntent(data);
            if (authHuaweiIdTask.isSuccessful()) {
                // 华为帐号登录成功
                AuthHuaweiId huaweiAccount = authHuaweiIdTask.getResult();
                Log.i(TAG, "signIn success");
                Log.i(TAG, "DisplayName: " + huaweiAccount.getDisplayName());
                Log.i(TAG, "AvatarUriString: " + huaweiAccount.getAvatarUriString());
                //登录成功处理
                onHuaweiIdLoginSuccess(huaweiAccount);
            } else {
                // 华为帐号登录失败
                String message = "signIn failed: " + ((ApiException) authHuaweiIdTask.getException()).getStatusCode();
                Toast.makeText(LoginActivity.this, message, Toast.LENGTH_SHORT).show();
            }
        }
    }


    /**
     * 使用SharedPreferences保存用户登录信息
     * @param context
     * @param username
     * @param password
     */


}